package com.heima.app.gateway.filter;

import com.heima.app.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
//设置过滤器等级,越小越先执行
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获得request与response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.判断是否登录
        if(request.getURI().getPath().contains("/login")){
            //是登陆放行
            return chain.filter(exchange);
        }
        //3.不是登录获取token
        String token = request.getHeaders().getFirst("token");
        //4.判断token是否存在

        if(StringUtils.isBlank(token)){
            //token为空不存在
            //向前端返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //结束本次请求
            return response.setComplete();
        }
        //5.token是否有效

        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //判断token是否过期
            int result = AppJwtUtil.verifyToken(claimsBody);
            if(result==1||result==2){
                //过期
                //向前端返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //结束本次请求
                return response.setComplete();
            }

            //获取用户ID
            Object userId = claimsBody.get("id");
            //将userid存入headers中,重置request中的headers.构造serverHttpRequest
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId.toString());
            }).build();
            //重置exchange中的request
            exchange.mutate().request(serverHttpRequest);

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        //6.放行
        return chain.filter(exchange);
    }
}
